Open
Conversation
|
Author
|
感谢回答。
int func(int a){
int res = 0;
/*
some code to change value res;
*/
return res;
}这正是单一出口原则的体现。
2.由于第一次提pr对markdown规范不是很熟悉,后续pr会注意的。 |
我见过比较好的 |
Contributor
很多人,包括我,视这种单一出口原则为反模式(anti-pattern)。不少代码库更青睐提前退出。 |
Contributor
|
c语言没有raii才需要单一出口,cpp不需要。 int do_something() {
int ret = 0;
FILE *fp = fopen("path.txt");
if (!fp) {
ret = -1;
goto out;
}
if (...) {
ret = -2;
goto out_fp;
}
out_fp:
fclose(fp);
out:
return ret;
}本质上是在用goto模拟析构函数的调用顺序,看似好像只有单一返回,实际上依然是提前返回的,每一次的goto语句不正是提前返回吗。 int do_something() {
int ret = 0;
ifstream fp("path.txt");
if (!fp) {
return -1;
}
if (...) {
return -2; // 自动调用 fp 的析构
}
return 0; // 自动调用 fp 的析构
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
1.提前结束语句的demo多出口违背了单一出口原则
2.lambda使用&捕获,并未直接使用外部变量,在()添加形参才对